package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author lvFF
 * @Date 2022/04/30/下午 5:56;
 * Description
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 验证码发送
     * @param user
     * @param session
     * @return
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        //判断手机号是否为空
        if (StringUtils.isNotBlank(phone)) {
            //生成验证码
            //Integer code = ValidateCodeUtils.generateValidateCode(4);
            //Integer code = 8888;
            String toCode ="8888";
            log.info("验证码code----------------{}", toCode);
            //将验证码保存到session中
            session.setAttribute(phone,toCode);
            //给手机发送验证码
           // SMSUtils.sendMessage("签名","魔板",phone,toCode);
            return R.success("手机验证码发送成功");
        }

        return R.error("手机验证码发送失败");
    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取手机号 和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session 获取验证码
        String codeSession = (String) session.getAttribute(phone);
        //比对验证码是否正确
        if (!StringUtils.equals(code,codeSession)){
            //不相同 不能登入
            return R.error("验证码输入错误");
        }
        //如果比对成功 就登入成果

        //判断手机 号 对应 是否为新用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //查询条件
        queryWrapper.eq("phone",phone);
        User one = userService.getOne(queryWrapper);
        //判断是否查到
        if (one == null){
            //没有查到 新用户 注册新用户
            one = new User();
            one.setPhone(phone);
            one.setStatus(1);
            //保存到数据库
            userService.save(one);
            //完成新用户注册
            //return R.success(user);
        }
        //建用户存入session中
        session.setAttribute("user",one.getId());

        return R.success(one);
    }
}
